import winreg
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime, date
import json
import os
from pydub import AudioSegment
from pydub.playback import play

path = os.path.realpath(__file__)
today = date.today()


class Ringer:
    def __init__(self):
        with open("ring.json", "r", encoding="utf-8") as f:
            self.data = json.load(f)

    def add_to_startup(self):
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Run",
            0,
            winreg.KEY_ALL_ACCESS,
        )
        winreg.SetValueEx(key, "class_ringer", 0, winreg.REG_SZ, f'"python.exe {path}"')
        winreg.CloseKey(key)

    def action_ring(self):
        audio = AudioSegment.from_wav("ring.wav")
        play(audio)
        with open("ringer.log", "a", encoding="utf-8") as f2:
            f2.write(f"{datetime.now()}: Ringer has run successfully.\n")

    def ringer(self):
        scheduler = BlockingScheduler()
        for i in self.data:
            scheduler.add_job(
                self.action_ring,
                "date",
                run_date=datetime(today.year, today.month, today.day, i[0], i[1]),
            )
        scheduler.start()


if __name__ == "__main__":
    ringer = Ringer()
    tester = winreg.OpenKey(
        winreg.HKEY_CURRENT_USER,
        r"Software\Microsoft\Windows\CurrentVersion\Run",
        0,
        winreg.KEY_ALL_ACCESS,
    )
    try:
        winreg.QueryValueEx(tester, "class_ringer")[0]
    except FileNotFoundError:
        ringer.add_to_startup()
    except Exception as e:
        with open("ringer.log", "a", encoding="utf-8") as f2:
            f2.write(f"{datetime.now()}: {e}\n")
    finally:
        winreg.CloseKey(tester)
        ringer.ringer()
